package com.totoro.tygeneratedragonblock.executor.condition.impl;

import com.totoro.tygeneratedragonblock.data.ConditionResult;
import com.totoro.tygeneratedragonblock.executor.condition.ConditionExecutor;
import com.totoro.tygeneratedragonblock.utils.JexlUtil;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.bukkit.entity.Player;

public class DefaultConditionExecutor implements ConditionExecutor {
    @Override
    public ConditionResult execute(String conditionText, Player player) {
        String[] split = conditionText.split("<>");
        String failReason = null;
        if(split.length == 2) {
            conditionText = split[0];
            failReason = split[1];
        }
        ConditionResult conditionResult = new ConditionResult(false, failReason);
        conditionText = getFinalConditionText(conditionText);
        try {
            Object result = JexlUtil.evaluateExpressions(conditionText);
            if (result instanceof Boolean) {
                conditionResult.setIsSuccess((Boolean) result);
                return conditionResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return conditionResult;
        }
        return conditionResult;
    }
}
